import React, {useEffect, useState} from 'react';
import {Button, Col, Form, Row, Select, message, Collapse, Space, Divider, Switch, Tooltip} from "antd";
import { useTranslation } from 'react-i18next';
import styles from './styles.module.less';
import {LineChartOutlined, SearchOutlined} from "@ant-design/icons";
import request from "@src/services/request";
import ContactDialogCom from "@src/components/ContactDialogCom";

const DCI = () => {
    const { t } = useTranslation();
    const [listPop, setListPop] = useState([]);
    const [pricelist, setPricelist] = useState([]);

    const [requirementModalVisible, setRequirementModalVisible] = useState(false);

    const {Panel} = Collapse;
    const text = <span>{t('Monitor the lowest internet connection prices for this route and receive price alerts by email.')}</span>;



    const showModal = () => {
        setRequirementModalVisible(true);
        console.log(requirementModalVisible)
    };

    const handleModalClose = () => {
        setRequirementModalVisible(false);
    };


    // const handleContainerClick = (event) => {
    //     const target = event.target;
    //     // 根据点击的具体元素执行相应的操作
    //     if (target.id === 'contact') {
    //         showModal()
    //     }
    // };

    const getListPop = async () => {
        try {
            const response = await request({
                url: '/price/listPop',
                method: 'get',
                data: {}
            });
            const formattedOptions = response.map(item => ({
                label: `${item.label}`, // 使用 label 和 desc 组合展示
                options: item.value.map(v => ({
                    label: (
                        <>
                            {v.label} <br/>
                            <span className={styles.subtext}> {v.desc} </span>
                        </>
                    ),
                    desc: v.label,
                    value: v.value // 使用你的实际字段名称替换
                })),
            }));
            setListPop(formattedOptions);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    useEffect(() => {
        getListPop();
    }, []);

    const onFinish = (values) => {
        console.log('Success:', values);

        const selectedSource = listPop.find(option => option.options.find(op => op.value === values.source));
        const sourceDesc = selectedSource ? selectedSource.options.find(op => op.value === values.source).desc : null;

        const selectedDestination = listPop.find(option => option.options.find(op => op.value === values.destination));
        const destinationDesc = selectedDestination ? selectedDestination.options.find(op => op.value === values.destination).desc : null;

        const response = request({
            url: '/price/dci',
            method: 'get',
            data: {
                source: values.source,
                sourceDesc: sourceDesc,
                destination: values.destination,
                destinationDesc: destinationDesc,
                contractTerm: values.contractTerm,
                bandwidth: values.bandwidth,
            }
        }).then(response => {
            console.log(response);
            setPricelist(response);
        });
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const CustomHeader = ({currency, baseFee, rttMs, index}) => (
        <div>
            <Row>
                <Col>{t('Line')} {index}</Col>
                <Col className={styles.price_money_list}>
                    <Row>
                        {currency} {baseFee}
                    </Row>
                    <Row>
                        {t('Estimated delay')}：{rttMs} ms
                    </Row>
                </Col>
            </Row>
        </div>
    );

    const handleChange = (selectedValue) => {
        let sortedList = [...pricelist]; // 创建一个新数组以确保状态更新
        if (selectedValue === 'price') {
            sortedList.sort((a, b) => a.result.baseFee - b.result.baseFee);
        } else if (selectedValue === 'latency') {
            sortedList.sort((a, b) => a.result.rttMs - b.result.rttMs);
        }
        setPricelist(sortedList); // 更新状态
    }

    return (
        <div className={styles.rightBg}>
            <div className={styles.price_tip}>{t('Do you want to know the DCI price? View now for free!')}</div>
            <Form
                name="dciForm"
                layout="vertical"
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <Row className={styles.searchDiv} gutter={[16, 16]} align="middle" justify="center">
                    <Col span={6}>
                        <Form.Item
                            label={t('Source')}
                            name="source"
                            rules={[{required: true, message: t('Please select source')}]}  // 设置来源为必填
                        >
                            <Select
                                showSearch
                                className={styles.select}
                                placeholder={t('Please select source')}
                                optionFilterProp="children"
                                filterOption={(input, option) => ((option?.desc?.toString().toLowerCase() ?? '').includes(input.toLowerCase()) || (option?.label?.toString().toLowerCase() ?? '').includes(input.toLowerCase()))}
                                filterSort={(optionA, optionB) =>
                                    (optionA?.desc ?? '').toLowerCase().localeCompare((optionB?.desc ?? '').toLowerCase())
                                }
                                options={listPop}
                            />
                        </Form.Item>
                    </Col>

                    <Col span={6}>
                        <Form.Item
                            label={t('Destination')}
                            name="destination"
                            rules={[{required: true, message: t('Please select your destination')}]}  // 设置目的地为必填
                        >
                            <Select
                                showSearch
                                className={styles.select}
                                placeholder={t('Please select your destination')}
                                optionFilterProp="children"
                                filterOption={(input, option) => ((option?.desc?.toString().toLowerCase() ?? '').includes(input.toLowerCase()) || (option?.label?.toString().toLowerCase() ?? '').includes(input.toLowerCase()))}
                                filterSort={(optionA, optionB) =>
                                    (optionA?.desc ?? '').toLowerCase().localeCompare((optionB?.desc ?? '').toLowerCase())
                                }
                                options={listPop}
                            />
                        </Form.Item>
                    </Col>

                    <Col span={3}>
                        <Form.Item
                            label={t('Contract duration')}
                            name="contractTerm"
                            rules={[{required: true, message: t('Please select the contract period')}]}  // 设置合约期限为必填
                        >
                            <Select
                                showSearch
                                className={styles.select}
                                placeholder={t('Please select the contract period')}
                                optionFilterProp="children"
                                filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                options={[
                                    {value: 'Daily', label: t('Every day')},
                                    {value: 'Weekly', label: t('Weekly')},
                                    {value: 'Monthly', label: t('Per month')},
                                    {value: 'Yearly', label: t('Each year')},
                                ]}
                            />
                        </Form.Item>
                    </Col>

                    <Col span={3}>
                        <Form.Item
                            label={t('Bandwidth')}
                            name="bandwidth"
                            rules={[{required: true, message: t('Please select bandwidth')}]}  // 设置带宽为必填
                        >
                            <Select
                                showSearch
                                className={styles.select}
                                placeholder={t('Please select bandwidth')}
                                optionFilterProp="children"
                                filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                options={[
                                    {value: '10', label: '10 Mbps'},
                                    {value: '50', label: '50 Mbps'},
                                    {value: '100', label: '100 Mbps'},
                                    {value: '200', label: '200 Mbps'},
                                    {value: '500', label: '500 Mbps'},
                                    {value: '1000', label: '1000 Mbps'},
                                ]}
                            />
                        </Form.Item>
                    </Col>

                    <Col span={4}>
                        <Form.Item>
                            <Button className={`${styles.dcc_bg_gradient} ${styles.mt20}`} type="primary"
                                    icon={<SearchOutlined/>} size="large" htmlType="submit">
                                {t('Query')}
                            </Button>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>

            {
                (pricelist && pricelist.length > 0) && <Row>
                    <Col span={16} style={{marginLeft: '12%'}}>
                        <Row>
                            <Col span={8}>{t('Price Results')}</Col>
                            <Col span={8}>
                                <LineChartOutlined style={{fontSize: '16px'}}/>
                                <Tooltip placement="topRight" title={text}>
                                    <span style={{margin: "0 10px"}}>{t('Tracking Prices')}</span>
                                </Tooltip>
                                <Switch style={{marginTop: "-3px", color: "#7d68ef", backgroundColor: "#7d68ef"}}
                                        size="small" checkedChildren={t('Open')} unCheckedChildren={t('Closure')} defaultChecked/>
                            </Col>
                            <Col span={8} style={{textAlign: "right"}}>
                                <span style={{margin: "0 10px"}}>{t('Sorting')}</span>
                                <Select defaultValue="price" style={{width: 120}} onChange={handleChange}
                                        options={[
                                            {
                                                value: 'price',
                                                label: t('Price'),
                                            },
                                            {
                                                value: 'latency',
                                                label: t('Delay'),
                                            }
                                        ]}
                                />
                            </Col>
                        </Row>
                        <Space direction="vertical" style={{width: '100%'}}>
                            <Collapse collapsible="header" defaultActiveKey={['0']}>
                                {pricelist.map((item, index) => (
                                    //添加判断item.result.baseFee == NaN时显示div
                                    item.result.baseFee !== null && !isNaN(item.result.baseFee) ? (

                                    <Panel
                                        header={<CustomHeader rttMs={item.result.rttMs.toFixed(0)} currency={item.currency}
                                                              baseFee={item.result.baseFee.toFixed(2)} index={index + 1}/>}
                                        style={{fontWeight: "bold", padding: "5px"}}
                                        key={item.key}>
                                        <Row>
                                            <Col span={12}>{t('Source port charges')}</Col>
                                            <Col span={12} className={styles.text_align_right}>$0.00</Col>
                                        </Row>
                                        <Row>
                                            <Col span={12}>{t('Destination Port Charges')}</Col>
                                            <Col span={12} className={styles.text_align_right}>$0.00</Col>
                                        </Row>

                                        <Row>
                                            <Col span={12}>{t('Line Fees')}</Col>
                                            <Col span={12}
                                                 className={styles.text_align_right}>{item.currency} {item.result.baseFee.toFixed(2)}</Col>
                                        </Row>
                                        <Divider/>
                                        <Row>
                                            <Col span={12}>{t('Total cost (including port)')}</Col>
                                            <Col span={12}
                                                 className={styles.text_align_right}>{item.currency} {item.result.baseFee.toFixed(2)}</Col>
                                        </Row>
                                        <Divider/>
                                        <Row>
                                            <Col span={12} className={styles.contact_div}>
                                                <Button type="primary" onClick={showModal} >{t('Contact Sales')}</Button>
                                            </Col>
                                            <Col span={12}>
                                                <Button type="primary"
                                                        className={styles.dcc_bg_gradient}>{t('Send me a quote by email')}</Button>
                                            </Col>
                                        </Row>
                                    </Panel>
                                    ) : (
                                        <div className={styles.no_result}>{t('No relevant data found')}</div>
                                    )

                                ))}
                            </Collapse>
                        </Space>
                    </Col>
                </Row>
            }
            <Row>
                {
                    (!pricelist || pricelist.length === 0) &&
                    <div className={styles.no_begin}>{t('Start exploring price results')}</div>
                }
            </Row>

            <ContactDialogCom requirementModalVisibleFrom={requirementModalVisible}
                              handleModalClose={handleModalClose}></ContactDialogCom>
        </div>
    );
};

export default DCI;
